//
//  JLLoginViewController.m
//  JLStyleApp
//
//  Created by JopYin on 15/8/18.
//  Copyright (c) 2015年 JLStyle. All rights reserved.
//

#import "JLLoginViewController.h"
#import "JLRegisterViewController.h"
#import "JLResetPwdViewController.h"
#import "JLUserinfoDelegate.h"
#import "JLUserinfo.h"
#import "AppDelegate.h"

@interface JLLoginViewController ()<UIScrollViewDelegate, UITextFieldDelegate, JLUserinfoDelegate>
{
    UIButton *doneInKeyboardButton;
    BOOL keyboardIsVisible;
}
@property (strong, nonatomic) UIScrollView *scrollview;

@property (strong, nonatomic) TTTAttributedLabel *titleLabel_en;
@property (strong, nonatomic) TTTAttributedLabel *titleLabel_cn;
@property (strong, nonatomic) UIView *registerView;
@property (strong, nonatomic) UIView *titleView;

@property (strong, nonatomic) UIButton *loginButton;
@end

@implementation JLLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.scrollview];
    [self.titleView addSubview:self.titleLabel_en];
    [self.titleView addSubview:self.titleLabel_cn];
    [self.scrollview addSubview:self.registerView];
    [self.scrollview addSubview:self.titleView];
    //设置此页面的背景色
    self.view.backgroundColor = [UIColor customControllerBackgroundColor];
    //配置界面
    [self createUI];
    //按钮
    [self.scrollview addSubview:self.loginButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setCustomBackgroundColor:GlobalColor];
    //注册键盘显示通知  观察到键盘将要显示的时候 我们使用keyboardWillShow
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘隐藏通知 观察到这个键盘将要消失的时候 我们执行 keyboardWillHide
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [userNameTexF becomeFirstResponder];
}

//退出时移除观察者
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 登陆
- (void)loginAction:(UIButton *)sender{
    if (isNullString(userNameTexF.text) || ![JFGlobalInstance validateNumber:userNameTexF.text]) {
        [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"(%>_<%)请输入手机号码." afterDelay:2.f];
        return;
    }
    if (isNullString(passWordTexF.text)) {
        [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"(%>_<%)请输入密码." afterDelay:2.f];
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    //TODO: 登录Api
    [JLUserinfo do_login:userNameTexF.text password:passWordTexF.text delegate:self];
}


// 去注册界面
- (void)goDoRegister{
    JLRegisterViewController *registerViewController = [[JLRegisterViewController alloc] init];
    [self.navigationController pushViewController:registerViewController animated:YES];
}

#pragma mark JLUserinfoDelegate
- (void)operatingResult:(BOOL)isOK stateCode:(int)state{
    [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
    if (isOK) {
        switch (state) {
            case 0:
            {
                [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"登录成功." afterDelay:2.f];
                //TODO: 登录成功，本地记录，然后进入首页
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setBool:YES forKey:@"isLogin"];
                AppDelegate *appDelegate = JLAppDelegate;
                [UIView transitionWithView:self.view
                                  duration:1.0
                                   options:UIViewAnimationOptionTransitionCrossDissolve
                                animations:^{
                                    [appDelegate.window removeFromSuperview];
                                }
                                completion:^(BOOL finished) {
                                    [appDelegate initHomeViewController];
                                }];
                
            }
                break;
            case 1:
                [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"密码不正确哦." afterDelay:2.f];
                break;
            case 2:
                [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"用户还没有注册哦." afterDelay:2.f];
                break;
            default:
                break;
        }
    }else{
        [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"可能网络错误吧." afterDelay:2.f];
    }
}

#pragma mark - keyboardWillShow
- (void)keyboardWillShow:(NSNotification *)notification
{
    keyboardIsVisible = YES;
    //判断doneInKeyboardButton==nil
    if (doneInKeyboardButton==nil && ![passWordTexF becomeFirstResponder]) {
        [self configDoneInKeyBoardButton];
    }
}

#pragma mark - keyboardWillHide
- (void)keyboardWillHide:(NSNotification *)notification
{
    keyboardIsVisible = NO;
    if (doneInKeyboardButton) {
        [doneInKeyboardButton removeFromSuperview];
        doneInKeyboardButton = nil;
        //让手机号输入框失去第一响应,确保每一响应都会去创建确认按钮
        [userNameTexF resignFirstResponder];
    }
}

//拖动将结束
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    keyboardIsVisible = YES;
    [self.view endEditing:YES];
}

-(void)createUI
{
    //文本框
    UITextField *phoneTextView = [[UITextField alloc] init];
    phoneTextView.delegate = self;
    phoneTextView.placeholder = @"手机号码";
    phoneTextView.backgroundColor = [UIColor whiteColor];
    phoneTextView.textColor = [UIColor customDarkPlaceColor];
    phoneTextView.font = JLBlodFont(16);
    phoneTextView.keyboardType = UIKeyboardTypeNumberPad;
    phoneTextView.returnKeyType = UIReturnKeyDone;
    phoneTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTextView.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    phoneTextView.leftViewMode = UITextFieldViewModeAlways;
    phoneTextView.frame = CGRectMake(0, 0, ScreenWidth, 50);
    [self.registerView addSubview:phoneTextView];
    userNameTexF = phoneTextView;
    
    //文本框
    UITextField *passTextView = [[UITextField alloc] init];
    passTextView.delegate = self;
    passTextView.placeholder = @"密码";
    passTextView.backgroundColor = [UIColor whiteColor];
    passTextView.textColor = [UIColor customDarkPlaceColor];
    passTextView.font = JLBlodFont(16);
    passTextView.returnKeyType = UIReturnKeyDone;
    passTextView.secureTextEntry = YES;
    passTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    passTextView.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    passTextView.leftViewMode = UITextFieldViewModeAlways;
    passTextView.frame = CGRectMake(0, 51, ScreenWidth, 50);
    [self.registerView addSubview:passTextView];
    passWordTexF = passTextView;
    
    UIButton *findButton = [UIButton buttonWithType:UIButtonTypeCustom];
    findButton.frame = CGRectMake(ScreenWidth - 100, self.registerView.center.y+50+10, 100, 25);
    [findButton setTitle:@"找回密码？" forState:UIControlStateNormal];
    findButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [findButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [findButton setBackgroundColor:[UIColor clearColor]];
    [findButton addTarget:self action:@selector(findPsd:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollview addSubview:findButton];
    
    
    
    NSString *registerStr = @"立即注册";
    
    UIFont *btnFont = [UIFont boldSystemFontOfSize:15];
    CGSize btnSize = [JFGlobalInstance sizeWithString:registerStr font:btnFont maxSize:CGSizeMake(MAXFLOAT,MAXFLOAT)];
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.frame = CGRectMake(ScreenWidth/2-btnSize.width/2, self.loginButton.center.y + 35, btnSize.width, btnSize.height);
    registerButton.titleLabel.font = btnFont;
    [registerButton setTitle:registerStr forState:UIControlStateNormal];
    [registerButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [registerButton setBackgroundColor:[UIColor clearColor]];
    [registerButton addTarget:self action:@selector(goDoRegister) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollview addSubview:registerButton];
    
    //关于下划线(attri画出来的不合适)
    UIView *line_xiahua = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth/2-btnSize.width/2, registerButton.center.y+btnSize.height/2+2, btnSize.width, 1)];
    line_xiahua.backgroundColor = [UIColor darkGrayColor];
    [self.scrollview addSubview:line_xiahua];
}

#pragma mark -实现button的点击事件
-(void)findPsd:(UIButton *)button
{
    JLResetPwdViewController *resetPwdViewController = [[JLResetPwdViewController alloc] init];
    [self.navigationController pushViewController:resetPwdViewController animated:YES];
}

#pragma mark - textField Delegate

//Return
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == userNameTexF) {
        //让密码输入框成为第一响应者
        [passWordTexF becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == userNameTexF) {
        //创建确认键
        [self configDoneInKeyBoardButton];
    }else{
        [doneInKeyboardButton removeFromSuperview];
        doneInKeyboardButton = nil;
    }
}

- (void)configDoneInKeyBoardButton{
    //初始化
    if (doneInKeyboardButton == nil)
    {
        doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [doneInKeyboardButton setTitle:@"确认" forState:UIControlStateNormal];
        [doneInKeyboardButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
        [doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
    }
    //每次必须从新设定“确认”按钮的初始化坐标位置
    doneInKeyboardButton.frame = CGRectMake(0, ScreenHeight+216, 122, 53);
    
    //由于ios8下，键盘所在的window视图还没有初始化完成，调用在下一次 runloop 下获得键盘所在的window视图
    [self performSelector:@selector(addDoneButton) withObject:nil afterDelay:0.0f];
}

#pragma mark -实现事件
- (void) addDoneButton{
    //获得键盘所在的window视图
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    [tempWindow addSubview:doneInKeyboardButton];// 注意这里直接加到window上
    
    if (keyboardIsVisible) {
        [UIView animateWithDuration:0.25 delay:0.0 options:7 << 16 animations:^{
            doneInKeyboardButton.transform = CGAffineTransformMakeTranslation(0, -269);
        } completion:^(BOOL finished) {
            keyboardIsVisible = NO;
        }];
    }else{
        doneInKeyboardButton.frame = CGRectMake(0, ScreenHeight-53, 122, 53);
    }
    
    
}

-(void)finishAction{
    [passWordTexF becomeFirstResponder];
}

#pragma mark-textField的代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //你的每一次输入的都会执行到这里
    return YES;
}

#pragma mark lazyload

- (UIButton *)loginButton{
    if (_loginButton==nil) {
        CGFloat registerButtonW = ScreenWidth-40;
        _loginButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2-registerButtonW/2, self.registerView.center.y+50+50, registerButtonW, 50)];
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor customLightPlaceColor] forState:UIControlStateHighlighted];
        _loginButton.backgroundColor = GlobalColor;
        _loginButton.titleLabel.font = JLBlodFont(18);
        _loginButton.layer.cornerRadius = 25;
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        
        [_loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (UIView *)titleView{
    if (_titleView==nil) {
        _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 120)];
        _titleView.backgroundColor = GlobalColor;
    }
    return _titleView;
}

- (UIView *)registerView{
    if (_registerView==nil) {
        _registerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.titleView.center.y+60+20, ScreenWidth, 101)];
        _registerView.backgroundColor = [UIColor customControllerBackgroundColor];
    }
    return _registerView;
}

- (TTTAttributedLabel *)titleLabel_en{
    if (_titleLabel_en==nil) {
        NSString *en_Value = @"Personal Resume";
        UIFont *font = [UIFont boldSystemFontOfSize:32];
        CGSize title_enSize = [JFGlobalInstance sizeWithString:en_Value font:font maxSize:CGSizeMake(ScreenWidth, MAXFLOAT)];
        
        _titleLabel_en = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20, 0, ScreenWidth, title_enSize.height)];
        _titleLabel_en.font = font;
        _titleLabel_en.textColor = [UIColor whiteColor];
        _titleLabel_en.text = en_Value;
    }
    return _titleLabel_en;
}

- (TTTAttributedLabel *)titleLabel_cn{
    if (_titleLabel_cn==nil) {
        NSString *cn_Value = @"简历·风";
        UIFont *font = [UIFont boldSystemFontOfSize:30];
        CGSize title_cnSize = [JFGlobalInstance sizeWithString:cn_Value font:font maxSize:CGSizeMake(ScreenWidth, MAXFLOAT)];
        
        CGFloat marginRight = ScreenWidth-title_cnSize.width-20;
        _titleLabel_cn = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(marginRight, self.titleLabel_en.center.y+30, title_cnSize.width, title_cnSize.height)];
        _titleLabel_cn.font = font;
        _titleLabel_cn.textColor = [UIColor whiteColor];
        _titleLabel_cn.text = cn_Value;
    }
    return _titleLabel_cn;
}

-(UIScrollView *)scrollview{
    if (_scrollview==nil) {
        _scrollview = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _scrollview.showsVerticalScrollIndicator = NO;
        _scrollview.showsHorizontalScrollIndicator = NO;
        _scrollview.delegate = self;
    }
    return _scrollview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
